package com.book.controller;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.request.AlipayTradeQueryRequest;
import com.book.util.AlipayConfig;
import com.book.util.ResultBack;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * @program:
 * @ClassName:
 * @description:
 * @author: zgc
 * @date:
 * @Version 1.0
 **/
@Controller
public class PayController {
    AlipayTradePagePayRequest alipayTradePagePayRequest;

    @Autowired
    public void setAlipayRequest(AlipayTradePagePayRequest alipayTradePagePayRequest) {
        this.alipayTradePagePayRequest = alipayTradePagePayRequest;
    }

    AlipayClient alipayClient;

    @Autowired
    public void setAlipayClient(AlipayClient alipayClient) {
        this.alipayClient = alipayClient;
    }

    AlipayConfig alipayConfig;

    @Autowired
    public void setAlipayConfig(AlipayConfig alipayConfig) {
        this.alipayConfig = alipayConfig;
    }

    /**
     * @param orderId 商户订单号，商户网站订单系统中唯一订单号，必填
     * @param total 付款金额，必填
     * @param name      订单名称，必填
     * @param body         商品描述，可空
     * @return
     * @throws AlipayApiException
     */
    @RequestMapping("/alipay/pay")
    @ResponseBody
    public String pay(String orderId, String total, String name, String body) throws AlipayApiException {

        alipayTradePagePayRequest.setBizContent("{\"out_trade_no\":\"" + orderId + "\","
                + "\"total_amount\":\"" + total + "\","
                + "\"subject\":\"" + name + "\","
                + "\"body\":\"" + body + "\","
                + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");
        //请求
        String result = alipayClient.pageExecute(alipayTradePagePayRequest).getBody();
        
        System.out.println("得到的结果：" + result);
        
        return result;
    }

    /**
     * @param out_trade_no 商户的订单编号      (两个参数二选一)
     * @param trade_no     支付宝的支付流水号  (两个参数二选一)
     * @return
     */
    @RequestMapping("/alipay/query")
    @ResponseBody
    public ResultBack queryPay(String out_trade_no,@RequestParam(defaultValue = "") String trade_no) throws AlipayApiException {

        // 注意这里的request和支付时候的request对象不一样
        AlipayTradeQueryRequest alipayRequest = new AlipayTradeQueryRequest();

        System.out.println("订单查询：-------------------------------------------");
        System.out.println("订单编号:"+out_trade_no);
        System.out.println("支付流水号:"+trade_no);

        alipayRequest.setBizContent("{\"out_trade_no\":\"" + out_trade_no + "\"," + "\"trade_no\":\"" + trade_no + "\"}");
        //请求
        String result = alipayClient.execute(alipayRequest).getBody();
        
        return ResultBack.success("订单查询成功", result);
    }

    /**
     *  说明：这个接口是支付成功之后，跳转回的路径。
     *  这里应该写我们的自己的订单处理逻辑
     *
     * @throws AlipayApiException
     * @throws UnsupportedEncodingException
     */
    @RequestMapping("/alipay/return_url")
    @ResponseBody
    public ResultBack return_url(HttpServletRequest request) throws AlipayApiException, UnsupportedEncodingException {
        //获取支付宝GET过来反馈信息
        Map<String, String> params = new HashMap<String, String>();
        Map<String, String[]> requestParams = request.getParameterMap();
        for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext(); ) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            //乱码解决，这段代码在出现乱码时使用
            valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
            params.put(name, valueStr);
        }

        boolean signVerified = AlipaySignature.rsaCheckV1(params, alipayConfig.getAlipay_public_key(), alipayConfig.getCharset(),
                alipayConfig.getSign_type()); //调用SDK验证签名

        //——请在这里编写您的程序（以下代码仅作参考）——
        if (signVerified) {
            //商户订单号
            String out_trade_no = request.getParameter("out_trade_no");
            //支付宝交易号
            String trade_no = request.getParameter("trade_no");
            //付款金额
            String total_amount = request.getParameter("total_amount");
            System.out.println("trade_no:" + trade_no + "<br/>out_trade_no:" + out_trade_no + "<br/>total_amount:" + total_amount);

            // 支付流程成功之后，我们就可以执行自己的流程，比如订单的支付状态改成 已支付

            return ResultBack.success( "支付成功", null);
        } else {
            return ResultBack.failure( "支付失败");
        }

    }

    @RequestMapping("/alipay/notify_url")
    @ResponseBody
    public ResultBack notify_url(HttpServletRequest request) throws AlipayApiException, UnsupportedEncodingException {
        //获取支付宝POST过来反馈信息
        Map<String, String> params = new HashMap<String, String>();
        Map<String, String[]> requestParams = request.getParameterMap();
        for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext(); ) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            //乱码解决，这段代码在出现乱码时使用
            valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
            params.put(name, valueStr);
        }

        boolean signVerified = AlipaySignature.rsaCheckV1(params, alipayConfig.getAlipay_public_key(), alipayConfig.getCharset(),
                alipayConfig.getSign_type()); //调用SDK验证签名

        if (signVerified) {
            //商户订单号
            String out_trade_no = request.getParameter("out_trade_no");
            //支付宝交易号
            String trade_no = request.getParameter("trade_no");
            //交易状态
            String trade_status = request.getParameter("trade_status");

            if (trade_status.equals("TRADE_FINISHED")) {
                //判断该笔订单是否在商户网站中已经做过处理
                //如果没有做过处理，根据订单号（out_trade_no）在商户网站的订单系统中查到该笔订单的详细，并执行商户的业务程序
                //如果有做过处理，不执行商户的业务程序
                //注意：
                //退款日期超过可退款期限后（如三个月可退款），支付宝系统发送该交易状态通知
                System.out.println("-------- 交易已经完成 ----------");

                return ResultBack.success( "交易完成", null);

            } else if (trade_status.equals("TRADE_SUCCESS")) {
                //判断该笔订单是否在商户网站中已经做过处理
                //如果没有做过处理，根据订单号（out_trade_no）在商户网站的订单系统中查到该笔订单的详细，并执行商户的业务程序
                //如果有做过处理，不执行商户的业务程序

                //注意：
                //付款完成后，支付宝系统发送该交易状态通知
                System.out.println("-------- 成功支付 ----------");
                return ResultBack.success("支付成功", null);
            }

            return ResultBack.success("成功", null);

        } else {
            return ResultBack.failure("失败");
        }
    }
    
}
